Page({
    data: {
        currentTab: 0, // 0-当前预约，1-历史预约
        currentReservation: [], // 当前预约数据
        historyReservation: [], // 历史借阅数据
        reservationList: [], // 预约列表数据
        selectedReservationId: null // 当前操作的预约记录ID

    },

    // 点击选项卡切换
    switchTab(e) {
        const tab = parseInt(e.currentTarget.dataset.tab);
        if (tab === 0) {
            this.currentReservation();
        } else if (tab === 1) {
            this.historyReservation();
        }
        this.setData({
            currentTab: tab
        });
    },

    // 滑动切换监听
    swiperChange(e) {
        const currentTab = e.detail.current;
        if (currentTab === 0) {
            this.currentReservation();
        } else if (currentTab === 1) {
            this.historyReservation();
        }
        this.setData({
            currentTab
        });
    },

    onLoad() {
        this.currentReservation();
        this.historyReservation();
    },

    // 时间格式化方法
    formatTime(timestamp) {
        if (!timestamp) return '未指定';
        const date = new Date(timestamp);
        // 补零处理，让月和日都是两位数，比如04月09日
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${date.getFullYear()}-${month}-${day}`;
    },

    // 签到
    onSingIn(e) {
        const reserveId = e.currentTarget.dataset.reserveid;
        const startTime = e.currentTarget.dataset.starttime;
        const endTime = e.currentTarget.dataset.endtime;

        const now = new Date();
        const now1 = now.getHours() * 60 + now.getMinutes();

        const isTime = now1 >= (startTime.slice(0, 2) * 60 + startTime.slice(3, 5) * 1) && now1 < (endTime.slice(0, 2) * 60 + endTime.slice(3, 5) * 1);

        if (!isTime) {
            wx.showToast({
                title: '签到失败，不在可签时间',
                icon: 'none'
            });
            return
        }

        const that = this;

        wx.request({
            url: 'http://localhost:8080/reservation/signIn?reserveId=' + reserveId,
            method: 'PUT',
            success: (res) => {
                if (res.data.code === 0) {
                    this.currentReservation();
                    wx.showToast({
                        title: '签到成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: res.data.msg || '操作失败',
                        icon: 'none'
                    });
                }
                this.onLoad();
            },
            fail: (error) => {
                wx.showToast({
                    title: '网络连接失败',
                    icon: 'none'
                });
            },
        });
    },

    // 取消预约
    onCancel(e) {
        const reserveId = e.currentTarget.dataset.reserveid;
        const that = this;

        wx.request({
            url: 'http://localhost:8080/reservation/cancel?reserveId=' + reserveId,
            method: 'PUT',
            success: (res) => {
                if (res.data.code === 0) {
                    this.currentReservation();
                    wx.showToast({
                        title: '取消预约成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: res.data.msg || '操作失败',
                        icon: 'none'
                    });
                }
                this.onLoad();
            },
            fail: (error) => {
                wx.showToast({
                    title: '网络连接失败',
                    icon: 'none'
                });
            },
        });
    },

    //获取当前预约记录
    currentReservation() {
        wx.request({
            url: 'http://localhost:8080/reservation/current?userId=' + wx.getStorageSync('userId'),
            method: 'GET',
            success: (res) => {
                if (res.statusCode === 200 && res.data.code === 0) {
                    const formattedData = res.data.data.map(item => ({
                        ...item,
                        reserveTime: this.formatTime(item.reserveTime),
                        startTime: item.startTime.slice(0, 5),
                        endTime: item.endTime.slice(0, 5)
                    }));

                    // 更新页面数据
                    this.setData({
                        currentReservation: formattedData,
                    });
                } else {
                    // 处理错误响应
                    wx.showToast({
                        title: res.data.msg || '加载失败',
                        icon: 'none'
                    });
                }
            }
        })
    },

    // 获取历史预约记录
    historyReservation() {
        wx.request({
            url: 'http://localhost:8080/reservation/history?userId=' + wx.getStorageSync('userId'),
            method: 'GET',
            success: (res) => {
                if (res.statusCode === 200 && res.data.code === 0) {
                    const currentDate = new Date(); // 当前时间
                    const formattedData = res.data.data.map(item => {
                        const reserveDate = new Date(item.reserveTime); // 原始reserveTime直接new（是时间戳或ISO格式）

                        // 计算日期差
                        const diffTime = currentDate - reserveDate;
                        const diffDays = diffTime / (1000 * 60 * 60 * 24);

                        return {
                            ...item,
                            reserveTime: this.formatTime(item.reserveTime), // 保持格式化后的时间
                            isOver7Days: diffDays <= 7 // 新增字段，true/false
                        };
                    });

                    // 更新页面数据
                    this.setData({
                        historyReservation: formattedData,
                    });
                } else {
                    // 处理错误响应
                    wx.showToast({
                        title: res.data.msg || '加载失败',
                        icon: 'none'
                    });
                }
            }
        })
    },

    onComment(e) {
        const reserveId = e.currentTarget.dataset.reserveid;
        const that = this;
        wx.showModal({
            title: '留下评论或反馈',
            content: '',
            showCancel: true,
            editable: true,
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {
                    wx.request({
                        url: 'http://localhost:8080/comment/add?reserveId=' + reserveId + '&content=' + res.content,
                        method: 'POST',
                        success: (res) => {
                            if (res.data.code === 0) {
                                wx.showToast({
                                    title: '反馈成功',
                                    icon: 'success'
                                });
                            } else {
                                wx.showToast({
                                    title: res.data.msg || '操作失败',
                                    icon: 'none'
                                });
                            }
                            this.onLoad();
                        },
                        fail: (error) => {
                            wx.showToast({
                                title: '网络连接失败',
                                icon: 'none'
                            });
                        },
                    });

                }
            }
        })
    },

    onChangeComment(e) {
        const reserveId = e.currentTarget.dataset.reserveid;
        const comment = e.currentTarget.dataset.comment;
        const that = this;
        wx.showModal({
            title: '修改反馈或评论',
            showCancel: true,
            editable: true,
            content: comment,
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {
                    wx.request({
                        url: 'http://localhost:8080/comment/update?reserveId=' + reserveId + '&content=' + res.content,
                        method: 'POST',
                        success: (res) => {
                            if (res.data.code === 0) {
                                wx.showToast({
                                    title: '修改成功',
                                    icon: 'success'
                                });
                            } else {
                                wx.showToast({
                                    title: res.data.msg || '操作失败',
                                    icon: 'none'
                                });
                            }
                            this.onLoad();
                        },
                        fail: (error) => {
                            wx.showToast({
                                title: '网络连接失败',
                                icon: 'none'
                            });
                        },
                    });

                }
            }
        })
    },

    getReplay(e) {
        const reserveId = e.currentTarget.dataset.reserveid;
        const replay = e.currentTarget.dataset.replay;
        const that = this;
        wx.showModal({
            title: '管理员回复',
            showCancel: false,
            // editable: true,
            content: replay,
            complete: (res) => {
                if (res.cancel) {

                }
            }
        })
    },


    getComment(e) {
        const reserveId = e.currentTarget.dataset.reserveid;
        const comment = e.currentTarget.dataset.comment;
        const that = this;
        wx.showModal({
            title: '我的反馈或评论',
            showCancel: false,
            // editable: true,
            content: comment,
            complete: (res) => {
                if (res.cancel) {

                }
            }
        })
    },
});